﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace NETCommon.Files
{
    /// <summary>
    /// Multiple Clients can access the same file at a time.
    /// </summary>
    public static class NSimpleLog
    {

        private static StreamWriter mLog;
        private static string _filename = "";
        private static FileStream myFile;
        private static Mutex mutFile = new Mutex();

        /// <summary>
        /// User Input file Name.
        /// Default is String.Empty.
        /// </summary>
        public static string OutputFile = "";
        /// <summary>
        /// Whether user provide absoluted path in the filename.
        /// Default  value is false.
        /// </summary>
        public static bool useAbsPathFile = false;
        /// <summary>
        /// Set/Get LogLevel,it will not log if currentLogLevel>LogLevel.
        /// Default LogLevel is 0, means log all.
        /// </summary>
        public static int LogLevel = 0;

        /// <summary>
        /// Add Log with currentLogLevel.
        /// </summary>
        /// <param name="Level">Current Log Level</param>
        /// <param name="msg">Message will be logged</param>
        public static void AddLog(int Level, string msg)
        {
            //if currentLevel >LogLevel then return;
            if (Level > LogLevel)
            {
                return;
            }
            //Lock for other threads inside CurrentClient
            mutFile.WaitOne();

            try
            {

                string FilePath = String.Format(@"{0}\Log\{1:yyyy_MM}\", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now);

                // Get currentFileName
                String currentFileName = "";
                if (String.IsNullOrEmpty(OutputFile))
                {
                    currentFileName =
                    System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                }
                else
                {
                    currentFileName = OutputFile;
                }

                //Set Path for log file
                if (!useAbsPathFile)
                {
                    _filename = FilePath;
                    if (!Directory.Exists(_filename)) Directory.CreateDirectory(_filename);
                    _filename += String.Format("{0}_{1}.log", DateTime.Today.Day.ToString().PadLeft(2, '0'), currentFileName);
                }
                else
                {
                    _filename = String.Format(@"{0}\{1}_{2}", AppDomain.CurrentDomain.BaseDirectory, DateTime.Today.Day.ToString().PadLeft(2, '0'), OutputFile);
                }


                myFile = new FileStream(_filename, FileMode.Append);
                mLog = new StreamWriter(myFile);

                // Open file and log into file
                mLog.WriteLine(String.Format("L:{0}{1:[yyyy/MM/dd HH:mm:ss]}{2}", Level, DateTime.Now, msg));
                mLog.Flush();

                //Close for other instanse of CurrentClient
                myFile.Close();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("AddLog:" + ex.Message);
            }
            finally
            {
                //Lock for other threads inside CurrentClient
                mutFile.ReleaseMutex();
            }

        }
        /// <summary>
        /// Get current file name.
        /// </summary>
        /// <returns>return current file name</returns>
        public static string GetFileName()
        {
            return _filename;
        }
        /// <summary>
        /// Show current log using window's notepad.
        /// </summary>
        public static void ShowLog()
        {
            if (!String.IsNullOrEmpty(_filename))
            {
                Process notePad = new Process();
                notePad.StartInfo.FileName = "notepad.exe";
                notePad.StartInfo.Arguments = NSimpleLog.GetFileName();
                notePad.Start();
            }
        }
        /// <summary>
        /// Add log with default CurrentLogLevel is 0.
        /// </summary>
        /// <param name="msg">Message will be logged</param>
        public static void AddLog(string msg)
        {
            AddLog(0, msg);
        }
    }

}
